package com.fmi.timedealer.plan;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

import com.fmi.timedealer.R;
import com.fmi.timedealer.R.id;
import com.fmi.timedealer.R.layout;
import com.fmi.timedealer.R.menu;
import com.fmi.timedealer.datamanager.IDataManager;
import com.fmi.timedealer.datamanager.SQLiteDataManager;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class PlansActivity extends ListActivity {

	private static final int ACTION_REQUES_CODE = 0;
	private static final int ACTIVITIES_REQUEST_CODE = 1;
	
	private ArrayList<Plan> plans = null;
	private IDataManager dbManager = null;
	private PlansAdapter adapter = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.plans);
		
		dbManager = new SQLiteDataManager("MyDB", this);
		plans = dbManager.getPlans();
		
		refreshAdapter();
	}
	
	private void refreshAdapter() {
		adapter = new PlansAdapter(this, R.layout.plan_row, plans);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		setListAdapter(adapter);
		
		ListView lv = getListView();
		registerForContextMenu(lv);
		
		// On Plan click
		lv.setOnItemClickListener(new OnItemClickListener() {
			
			public void onItemClick(AdapterView<?> parent, View view,
				int position, long id) {
				Intent i = new Intent(PlansActivity.this, PlanPlannedActivity.class);
				i.putExtra(PlanPlannedActivity.PLANNED_ACTIVITY_BUNDLE_KEY, plans.get(position).getId());
				i.putExtra(PlanPlannedActivity.PLANNED_ACTIVITY_NAME_BUNDLE_KEY, plans.get(position).getName());
				startActivityForResult(i, ACTIVITIES_REQUEST_CODE);
			}
		});
		
		adapter.notifyDataSetChanged();
	}

	@Override
	protected void onResume() {
		super.onResume();
		
		refreshAdapter();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.plans_menu, menu);
	    return true;
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch (item.getItemId()) {
	        
			case R.id.add_plan: {
	        	Intent i = new Intent(PlansActivity.this, ManagePlanActivity.class);
				i.putExtra(ManagePlanActivity.PLAN_BUNDLE_KEY, new Plan());
				startActivityForResult(i, ACTION_REQUES_CODE);
	        	return true;
	        }
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
		menu.setHeaderTitle(plans.get(info.position).getName());
		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.manage_plan, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
	    
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	    
		switch (item.getItemId()) {
	        case R.id.edit_plan: {
	        	Intent i = new Intent(PlansActivity.this, ManagePlanActivity.class);
				i.putExtra(ManagePlanActivity.PLAN_BUNDLE_KEY, plans.get(info.position));
				startActivityForResult(i, ACTION_REQUES_CODE);
	        	return true;
	        }
	        case R.id.delete_plan: {
	            deletePlan(info.position);
	        	return true;
	        }
	        default:
	            return super.onContextItemSelected(item);
	    }
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == ACTION_REQUES_CODE) {
			if (resultCode == RESULT_OK) {
				Bundle extras = data.getExtras();
				Plan plan = (Plan)extras.getSerializable(ManagePlanActivity.PLAN_BUNDLE_KEY);
				
				updatePlan(plan);
			}
		}
	}
	
	private void updatePlan(Plan plan) {
		
		int position = -1;
		for (int i = 0; i < plans.size(); i++) {
			if (plans.get(i).getId() == plan.getId()) {
				position = i;
				break;
			}
		}
		
		if (position < 0) {
			// Add new object to the collection
			plans.add(plan);
		}
		else {
			// Update object 
			plans.set(position, plan);
		}
		
		adapter.notifyDataSetChanged();
		
		Toast.makeText(this, plan.getName() + " was successfully saved", Toast.LENGTH_SHORT).show();
	}
	
	private void deletePlan(int position) {
		boolean deleted = dbManager.deletePlan(plans.get(position));
		if (deleted) {
			Plan deletedPlan = plans.get(position);
			plans.remove(position);
			refreshAdapter();
			
			Toast.makeText(this, deletedPlan.getName() + " was successfully deleted", Toast.LENGTH_SHORT).show();
		}
	}

	private class PlansAdapter extends ArrayAdapter<Plan> {
		
        private ArrayList<Plan> items;

        public PlansAdapter(Context context, int textViewResourceId, ArrayList<Plan> items) {
                super(context, textViewResourceId, items);
                this.items = items;
        }
        
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
                
        	View v = convertView;
                if (v == null) {
                    LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    v = vi.inflate(R.layout.item_row, null);
                }
                
                Plan p = items.get(position);
                if (p != null) {
                	TextView tvName = (TextView)v.findViewById(R.id.itemName);
                    TextView tvInfo = (TextView)v.findViewById(R.id.itemInfo);
                    TextView tvStatus = (TextView)v.findViewById(R.id.itemStatus);
                    ProgressBar progressBar = (ProgressBar)v.findViewById(R.id.itemProgressBar);
                    
                    double plannedTime = getPlannedTimeForPlan(p);
                    double spentTime = getSpentTimeForPlan(p);
                    double progress = 100;
                    if (spentTime < plannedTime) {
                    	progress = (spentTime / plannedTime) * 100;
                    }
                    progressBar.setProgress((int)progress);
                    if (tvName != null) {
                    	tvName.setText(p.getName());
                	}
                    if (tvInfo != null) {
                    	tvInfo.setText(p.getDescription());
                    }
                    if (tvStatus != null) {
                    	DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");

                    	tvStatus.setText("Start: " + dateFormat.format(p.getStart()) + "\t " +
                    			"End: " + dateFormat.format(p.getEnd()));
                    }
                }
                return v;
        }
        
        private double getPlannedTimeForPlan(Plan plan) {
        	
        	double result = 0;
        	ArrayList<PlannedActivity> activities = dbManager.getPlannedActivities(plan.getId());
        	for(PlannedActivity activity : activities) {
        		result += activity.getDuration();
        	}
        	return result*60;
        }
        
        private double getSpentTimeForPlan(Plan plan) {
        	
        	double result = 0;
        	ArrayList<PlannedActivity> activities = dbManager.getPlannedActivities(plan.getId());;
        	for(PlannedActivity activity : activities) {
        	double spent = dbManager.getTimeSpentForPlannedActivity(activity);
        		if (spent > activity.getDuration() * 60) {
        			result += activity.getDuration() * 60;
        		} else {
        			result += spent;
        		}
        	}
        	return result;
        }
	}
	
}
